package com.mopa.http;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
public class QzoneUploadPic {
	private Handler mHandler;
	private OnUploadListener mUploadListener;
	String mAccessToken=null;
	String mAppid=null;
	String mOpenId=null;
	public interface OnUploadListener{
		void onStart();//开始
		void onSuncces(String sMsg);//成功
		void onFail(int ret,String fMsg);//失败
	}
	public  void uploadPic(Handler handler,Bundle baseParams,OnUploadListener listener) {
		mHandler=handler;
		mUploadListener=listener;
		mUploadListener.onStart();
		String mPicPath=baseParams.getString("picPath");
		String mContent=baseParams.getString("content");
		mAccessToken=baseParams.getString("accessToken");
		mAppid=baseParams.getString("appId");
		mOpenId=baseParams.getString("openId");
		Log.e("debug", "mAccessToken:"+mAccessToken+"mAppid:"+mAppid+"mOpenId:"+mOpenId);
		if(!satisfyConditions())
		{
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mUploadListener.onFail(0,"缺少必要的Oauth数据,请先登录");
				}
			});
			return;
		}
		File picFile = new File(mPicPath);
		if(picFile == null || !picFile.exists())
		{
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mUploadListener.onFail(0,"无效图片文件");
				}
			});
			return;
		}
		Bundle bundle = null;
		bundle = new Bundle();
		byte[] buff = null;
		try {
			InputStream is = new FileInputStream(picFile);
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while( (len = is.read(buffer)) !=-1 ){
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			is.close();
			buff = outSteam.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		bundle.putByteArray("picture", buff);
		bundle.putString("photodesc", mContent);
		bundle.putString("title", "mopa_" + System.currentTimeMillis() + ".png");
		QzoneAPI.uploadPic(mAccessToken, mAppid, mOpenId, bundle, new Callback() {
			
			public void onSuccess(final Object obj) {
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						mUploadListener.onSuncces(obj.toString());
					}
				});
			}
			public void onFail(final int ret, final String msg) {
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						mUploadListener.onFail(ret, msg);
					}
				});
			}
		});
	}
	public boolean satisfyConditions() {
		return TextUtils.isEmpty(mAccessToken) && TextUtils.isEmpty(mAppid)&&TextUtils.isEmpty(mOpenId);
	}

}
